# -*- coding: utf-8 -*-
class PurchaseOrder < ActiveRecord::Base
  has_many :purchase_order_details ,:dependent => :destroy  #级联删除子表
  has_many :warehousing_entry
  #belongs_to :sale_order
  belongs_to :employee
  belongs_to :vendor
  belongs_to :order_type
  belongs_to :department
  belongs_to :company
  belongs_to :auditor, :class_name => 'Employee', :foreign_key => 'auditor_id'
  belongs_to :warehouse_employee, :class_name => 'Employee', :foreign_key => 'warehouse_employee_id'

  #对比采购与入库的数量差别，这里只把已经撤消的排除在外，其它的状态比较申请状态的入库，我们都计算在内。所以在很多地方要把所有的申请都排除在外时，操作才可以顺畅。
  #这里是检查不出另一种情况的，就是入库比采购还多的情况，这里只能查询出入库比采购少的情况。
  scope :diff_purchase_entry, lambda { |purchaseOrderId| joins("po left join purchase_order_details pod on po.id = pod.purchase_order_id
                                  left join warehousing_entries we on we.purchase_order_id = po.id AND we.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
                                  left join warehousing_entry_details wed on wed.warehousing_entry_id = we.id AND pod.product_id = wed.product_id
                                  ").where("po.id = ?",purchaseOrderId).select("pod.product_id,sum(pod.quantity) pod_quantity,ifnull(sum(wed.quantity),0) wed_quantity").group("wed.product_id").having("pod_quantity - wed_quantity != 0") }

                                
  #def self.findAllPurchaseOrders  conditionsStr,conditionsHash,paramsHash
  #    find(
  #      :all,
  #      :conditions => [conditionsStr,conditionsHash],
  #      :include => [:employee,:department,:vendor,:auditor,:warehouse_employee,{:purchase_order_details=>:sale_order}],
  #      :offset => paramsHash[:offset],
  #      :limit => paramsHash[:limit],
  #    :order => 'purchase_orders.updated_at DESC'
  #    )
  #end


  scope :findAllPurchaseOrders, ->(conditionsStr,conditionsHash,paramsHash) { includes([:employee,:department,:vendor,:auditor,:warehouse_employee,{:purchase_order_details=>:sale_order}]).where([conditionsStr,conditionsHash]).offset(paramsHash[:offset]).limit(paramsHash[:limit]).order('purchase_orders.updated_at DESC')}
  #def self.countAllPurchaseOrders  conditionsStr,conditionsHash
  #    count(
  #      :all,
  #      :include=>[:purchase_order_details],
  #      :conditions => [conditionsStr,conditionsHash]#,
  #     #:include=>[:employee,:department,:vendor,:auditor,:warehouse_employee,{:purchase_order_details=>{:sale_order_detail=>:sale_order}}]
  #    )
  #end

  scope :countAllPurchaseOrders, ->(conditionsStr,conditionsHash) { includes([:purchase_order_details]).where([conditionsStr,conditionsHash]).count()}
end
